package com.wechat.utils;

import com.google.gson.Gson;
import com.wechat.constants.PropertiesConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * @author why
 * @date 2017/12/20 0020
 */
public class SignUtils {
    public static final Gson gson = new Gson();
    private static final Logger LOGGER = LoggerFactory.getLogger(SignUtils.class);
    /**
     * @param signature   消息加解密密钥 EncodingAESKey
     * @param timestamp   时间戳
     * @param nonce       随机字符串
     * @return
     */
    public static boolean checkSignature(String signature, String timestamp, String nonce) {
        //WechatToken 是登陆公众号后，左边的菜单，开发-》基本配置页面中的服务器配置的令牌，也就是token
        String[] arr = new String[]{PropertiesSingleton.newInstance().getProperties().getProperty(PropertiesConstants.WXTOKEN), timestamp, nonce};
        // 将token、timestamp、nonce三个参数进行字典排序
        Arrays.sort(arr);
        StringBuilder content = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            content.append(arr[i]);
        }
        String tmpStr = signature(content.toString());
        // 将sha1加密后的字符串与signature对比
        return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
    }

    /**
     * 将字节数组转换为十六进制字符串
     *
     * @param byteArray
     * @return
     */
    public static String byteToStr(byte[] byteArray) {
        StringBuilder strDigest = new StringBuilder("");
        for (int i = 0; i < byteArray.length; i++) {
            strDigest.append(byteToHexStr(byteArray[i]));
        }
        return strDigest.toString();
    }

    /**
     * 将字节转换为十六进制字符串
     *
     * @param myByte
     * @return
     */
    public static String byteToHexStr(byte myByte) {
        char[] digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        char[] tempArr = new char[2];
        tempArr[0] = digit[(myByte >>> 4) & 0X0F];
        tempArr[1] = digit[myByte & 0X0F];
        String s = new String(tempArr);
        return s;
    }


    public static String signature(String str){
        MessageDigest md = null;
        String tmpStr = null;
        try {
            md = MessageDigest.getInstance("SHA-1");
            // 将三个参数字符串拼接成一个字符串进行sha1加密
            byte[] digest = md.digest(str.toString().getBytes());
            tmpStr = byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return  tmpStr;
    }


    public static String getNonceStr() {
        Random random = new Random();
        return UUID.randomUUID().toString();
    }

    public static String getTimeStamp() {
        return String.valueOf(System.currentTimeMillis() / 1000);
    }


}
